package com.conduit.comnands;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.conduit.commands.prototype.AbstractCommand;
import com.conduit.enums.ResultCode;

public class DownloadFileCommand extends AbstractCommand {

	public DownloadFileCommand() {
		// download file <URL> <save as>
		commandSyntax = "download file\\s{2,}(.*)\\s{2,}(.*)";
	}

	@Override
	public void executeWithArgs(String args) {
		// validate command's syntax
		if (!args.matches(commandSyntax)) {
			setResult("Error in Command's syntax (\"" + args + "\")");
			setResultCode(ResultCode.Error);
			return;
		}
		Matcher matcher = Pattern.compile(commandSyntax).matcher(args);
		if (matcher.find()) {
			String url = matcher.group(1);
			String saveAs = matcher.group(2);
			try {
				saveUrlAsFile(saveAs, url);
				setResult("File Was Successesfuly Downloaded to " + saveAs);
				setResultCode(ResultCode.Successes);
			} catch (Exception e) {
				setResult(e.getMessage());
				setResultCode(ResultCode.Error);
			}
		}

	}

	private void saveUrlAsFile(String filename, String urlString)
			throws MalformedURLException, IOException {
		BufferedInputStream in = null;
		FileOutputStream fout = null;
		try {
			in = new BufferedInputStream(new URL(urlString).openStream());
			fout = new FileOutputStream(filename);

			byte data[] = new byte[1024];
			int count;
			while ((count = in.read(data, 0, 1024)) != -1) {
				fout.write(data, 0, count);
			}
		} finally {
			if (in != null)
				in.close();
			if (fout != null)
				fout.close();
		}
	}

	@Override
	public String getCommandName() {
		return "Download File";
	}

}
